<template>
    <div>
        <div>{{tip}}</div>
        <button @click="startRecording">开始</button>
        <button @click="endRecording">结束</button>
        <h1>token获取结果</h1>
        <div>{{tokenR}}</div>
        <h1>音频识别结果：</h1>
        <div>{{recognizeR}}</div>
    </div>
</template>
<script>
    import RecordRTC from 'recordrtc'
    import {
        sougou as sougouAPI
    } from '@/api'
import { setTimeout } from 'timers';

    export default {
        data() {
            return {
                recorder: null,
                tokenR: null,
                recognizeR: null,
                audioType: 'pcm',
                tip: '',
                timeTip: null,
            }
        },
        async mounted() {
            this.recorder = Recorder({
                type: 'wav'
            });
        },
        methods: {
            async startRecording() {
                let VM = this;
                this.tip = '正在录音';
                
                let time =0;
                this.timeTip = setInterval(()=>{
                     ++time;
                     this.tip = `正在录音：${time}s`
                },1000);

                this.recorder.open(function () { //打开麦克风授权获得相关资源
                    VM.recorder.start(); //开始录音
                }, function (msg, isUserNotAllow) { //用户拒绝未授权或不支持
                    //dialog&&dialog.Cancel(); 如果开启了弹框，此处需要取消
                    console.log((isUserNotAllow ? "UserNotAllow，" : "") + "无法录音:" + msg);
                });
            },
            async endRecording() {
                let VM = this;
                this.tip = '';
                clearTimeout(this.timeTip);

                this.recorder.stop(function (blob, duration) { //到达指定条件停止录音
                    console.log(URL.createObjectURL(blob), "时长:" + duration + "ms");
                    VM.recorder.close(); //释放录音资源

                    var reader = new FileReader();
                    reader.readAsDataURL(blob);
                    reader.onloadend = async function () {
                        VM.zhiyin(reader.result);
                    }
                }, function (msg) {
                    console.log("录音失败:" + msg);
                });
            },
            async zhiyin(data) {
                let VM = this;
                let tokenR = await sougouAPI.getToken();
                if (tokenR && tokenR.data && tokenR.data.token) {
                    VM.tokenR = tokenR.data;
                    let recognizeR = await sougouAPI.recognize(data, tokenR.data.token);
                    if (recognizeR && recognizeR.data) {
                        VM.recognizeR = recognizeR.data;
                    } else {
                        VM.recognizeR = '识别失败';
                    }
                } else {
                    VM.tokenR = '获取失败';
                    VM.recognizeR = '识别失败';
                }
            },
        },
    }
</script>
<style>

</style>